import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { Store } from '@ngxs/store';
import { SystemSelector } from '../../store/system/system.selector';
import { SystemAction } from '../../store/system/system.action';
import { AutoUnsubscribe } from 'ngx-auto-unsubscribe-decorator';

@Component({
  selector: 'app-config',
  templateUrl: './config.component.html',
  styleUrls: ['./config.component.scss'],
})
export class ConfigComponent implements OnInit {
  @AutoUnsubscribe() loading$ = this.store.select(SystemSelector.loading);
  list: any = [];

  @ViewChild('backupInput') backupInput!: ElementRef;
  @ViewChild('saveInput') saveInput!: ElementRef;
  param: any = {
    name: '',
    saveFolder: '',
    backupFolder: '',
  };

  constructor(
      private store: Store,
  ) {
    this.store.select(SystemSelector.configList).subscribe(r => this.list = r);
  }

  ngOnInit() {
    this.store.dispatch(new SystemAction.LoadConfigList());
  }

  changeSaveFolder(event: any) {
    const inputElement = event.target;
    if (!inputElement || !inputElement.files || inputElement.files.length === 0) return;
    this.param.saveFolder = inputElement.files[0].path;
  }

  changeBackupFolder(event: any) {
    const inputElement = event.target;
    if (!inputElement || !inputElement.files || inputElement.files.length === 0) return;
    this.param.backupFolder = inputElement.files[0].path;
  }

  configSave() {
    this.store.dispatch(new SystemAction.ConfigSave(JSON.parse(JSON.stringify(this.param)))).subscribe(() => {
      this.param = {};
    });
  }

  configNew() {
    this.store.dispatch(new SystemAction.ConfigNew(JSON.parse(JSON.stringify(this.param)))).subscribe(() => {
      this.param = {};
    });
  }

  setDefaultConfig(data: any) {
    this.store.dispatch(new SystemAction.SetDefaultConfig(data));
  }

  update(data: any) {
    this.param = JSON.parse(JSON.stringify(data));
  }

  delete(data: any) {
    this.store.dispatch(new SystemAction.DeleteConfig(data));
  }
}
